<template>
	<login-register title="欢迎登录" tips="输入账号密码进行登陆" class="login_page_wrapper">
		<el-form ref="loginForm" :rules="formRules" :model="loginForm">
			<el-form-item prop="account">
				<sw-custom-input
					input-type="email"
					v-model="loginForm.account"
					placeholder="请输入您的用户账号"
					prefix-icon="sw-icon-login-email"
					@keyup.enter.native="handleSubmitLogin"
				/>
			</el-form-item>
			<el-form-item prop="password">
				<el-input
					show-password
					auto-complete="new-password"
					prefix-icon="sw-icon-login-pass"
					placeholder="请输入您的登录密码"
					v-model="loginForm.password"
					@keyup.enter.native="handleSubmitLogin"
				></el-input>
			</el-form-item>
			<el-form-item prop="imageCode" v-if="!!verifyCodeImg">
				<sw-custom-input
					maxlength="4"
					input-type="capital"
					placeholder="请输入验证码"
					v-model="loginForm.imageCode"
					prefix-icon="sw-icon-verify-code"
					@keyup.enter.native="handleSubmitLogin"
				/>
				<img class="verify" :src="verifyCodeImg" @click="getVerifyCode" />
			</el-form-item>
			<el-form-item>
				<el-button class="submit" type="primary" @click="handleSubmitLogin" :loading="btnLoading">登录</el-button>
			</el-form-item>
		</el-form>
	</login-register>
</template>

<script>
import { mapGetters, mapActions } from 'vuex';
import { login, genVerifyCode } from '@/api/login';
import loginRegister from '@/views/common/loginRegister';
export default {
	components: { loginRegister },
	data() {
		return {
			loading: false,
			verifyCodeImg: '',
			loginForm: { account: '', password: '', imageCode: '' },
			formRules: {
				account: [{ required: true, message: '请输入用户账号', trigger: 'blur' }],
				password: [{ required: true, message: '请输入用户密码', trigger: 'blur' }],
				imageCode: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
			},
			btnLoading: false
		};
	},
	computed: { ...mapGetters(['siteInfo']) },
	mounted() {
		this.getVerifyCode();
	},
	methods: {
		...mapActions(['loginRequest']),
		//提交登录
		handleSubmitLogin() {
			this.$refs['loginForm'].validate((vail) => {
				if (!vail) return false;
				this.btnLoading = true;
				this.loginRequest(this.loginForm)
					.then(async (res) => {
						await this.$store.dispatch('getSiteConfig');
						this.$showCustomMessage('success', '登录成功');
						this.$router.push({ path: '/front' });
						this.btnLoading = false;
					})
					.catch(() => {
						this.getVerifyCode();
						this.btnLoading = false;
					});
			});
		},

		//获取验证码
		async getVerifyCode() {
			this.$set(this.loginForm, 'imageCode', '');
			genVerifyCode('123').then((res) => {
				this.verifyCodeImg = res.data;
			});
		}
	}
};
</script>
